package com.zz.study.sharding.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy.PropertyNamingStrategyBase;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.*;

/**
 * Created by Administrator on 2018/6/29 0029.
 */
public class JsonUtil {
    public static final ObjectMapper INSTANCE = new ObjectMapper();
    public static final ObjectMapper PASCAL_CASE_INSTANCE;

    public JsonUtil() {
    }

    public static String serialize(Object object) {
        try {
            String value = INSTANCE.writeValueAsString(object);
            return value;
        } catch (JsonProcessingException var3) {
            throw new RuntimeException(var3);
        }
    }

    public static <T> T deserialize(String json, Class<T> clazz) {
        Object object = null;

        try {
            object = INSTANCE.readValue(json, TypeFactory.rawClass(clazz));
            return (T) object;
        } catch (JsonProcessingException var4) {
            throw new RuntimeException(var4);
        } catch (IOException var5) {
            throw new UncheckedIOException(var5);
        }
    }

    static {
        INSTANCE.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        PASCAL_CASE_INSTANCE = new ObjectMapper();
        PASCAL_CASE_INSTANCE.setPropertyNamingStrategy(new PropertyNamingStrategyBase() {
            @Override
            public String translate(String propertyName) {
                return StringUtils.capitalize(propertyName);
            }
        });
    }

    public static JSONObject string2Json(String str){
        return JSON.parseObject(str);
    }


    public static JSONArray string2JSONArray(String str){
        return JSON.parseArray(str);
    }

    public static Map<String, Object> parseJSON2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject json = JSONObject.parseObject(jsonStr);
        for (Object k : json.keySet()) {
            Object v = json.get(k);
            if (v instanceof JSONArray) {
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                Iterator<Object> it = ((JSONArray) v).iterator();
                while (it.hasNext()) {
                    JSONObject json2 = (JSONObject) it.next();
                    list.add(parseJSON2Map(json2.toString()));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }
}
